package com.xdjd.mobile.system.config;


import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisConfig {

    private static Logger logger = Logger.getLogger(RedisConfig.class);
    @Value("${spring.redis.database}")
    private String database;
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${spring.redis.port}")
    private String port;
    @Value("${spring.redis.timeout}")
    private String timeout;
    @Value("${spring.redis.pool.max-idle}")
    private String maxIdle;
    @Value("${spring.redis.pool.min-idle}")
    private String minIdle;
    @Value("${spring.redis.pool.max-active}")
    private String maxActive;
    @Value("${spring.redis.pool.max-wait}")
    private String maxWait;

    @Bean
    public JedisPoolConfig getRedisConfig() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxIdle(Integer.parseInt(maxIdle));
        config.setMinIdle(Integer.parseInt(minIdle));
        config.setMaxWaitMillis(Long.parseLong(maxWait));
        config.setMaxTotal(Integer.parseInt(maxActive));
        return config;
    }

    @Bean
    public JedisConnectionFactory getConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        JedisPoolConfig config = getRedisConfig();
        factory.setPoolConfig(config);
        factory.setDatabase(Integer.parseInt(database));
        factory.setHostName(host);
        factory.setPassword(password);
        factory.setTimeout(Integer.parseInt(timeout));
        factory.setPort(Integer.parseInt(port));
        logger.info("JedisConnectionFactory bean init success.");
        return factory;
    }


    @Bean
    public RedisTemplate<?, ?> getRedisTemplate() {
        RedisTemplate<?, ?> template = new StringRedisTemplate(getConnectionFactory());
        return template;
    }

    @Bean
    public StringRedisTemplate getStringRedisTemplate() {
        StringRedisTemplate template = new StringRedisTemplate(getConnectionFactory());
        return template;
    }
}
